package org.lgy.sso_client.filter;


import cn.hutool.core.util.StrUtil;
import org.lgy.sso_comment.constant.AuthConst;
import org.lgy.sso_comment.storage.SessionStorage;
import org.lgy.sso_comment.util.EncryptUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 *
 */
@WebFilter(filterName = "LoginFilter", urlPatterns = "/*")
public class LoginFilter implements Filter {

	@Override
	public void destroy() {}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		HttpSession session = request.getSession();
		String url = request.getRequestURL().toString();

		if ("/test".equals(request.getRequestURI().replace(request.getContextPath(), ""))) {
			chain.doFilter(req, res);
			return;
		}

		// 已经登录，放行
		Boolean isLogin = (Boolean) session.getAttribute(AuthConst.IS_LOGIN);
		if (isLogin != null && isLogin) {
			chain.doFilter(req, res);
			return;
		}
		// 从认证中心回跳的带有token的请求，有效则放行
		String token = request.getParameter(AuthConst.TOKEN);
		if (token != null) {
			response.sendRedirect(AuthConst.TOKEN_CHECK_URL + "?" + AuthConst.TOKEN + "=" + token + "&" + AuthConst.CLIENT_URL + "=" + url);
			return;
		}

		String tokenCheck = request.getParameter(AuthConst.TOKEN_CHECK);
		if ("check".equals(tokenCheck)) {
			String result = request.getParameter(AuthConst.TOKEN_CHECK_RESULT);
			String loginToken = request.getParameter(AuthConst.LOGIN_TOKEN);
			if (StrUtil.isNotBlank(result)) {
				if ("pass".equals(EncryptUtil.aesDecrypt(result))) {
					session.setAttribute(AuthConst.IS_LOGIN, true);
					session.setAttribute(AuthConst.TOKEN, loginToken);
					// 存储，用于注销
					SessionStorage.INSTANCE.set(loginToken, session);
					chain.doFilter(req, res);
					return;
				} else {
					// 跳往失败界面
					System.out.println("token 验证失败");
					response.sendRedirect(request.getContextPath() + "/test");
					return;
				}
			}
		}

		// 被动注销，即从认证中心发送的注销请求
		token = request.getParameter(AuthConst.LOGOUT_REQUEST);
		if (StrUtil.isNotBlank(token)) {
			session = SessionStorage.INSTANCE.get(token);
			if (session != null) {
				try {
					session.invalidate();
				} catch (IllegalStateException e) {
					System.out.println("当前系统已退出登录，" + e.getMessage());
				}
				System.out.println(request.getContextPath() + " 被动退出登录");
			}
			return;
		}

		// 重定向至登录页面，并附带当前请求地址
		response.sendRedirect(AuthConst.LOGIN_URL + "?" + AuthConst.CLIENT_URL + "=" + url);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}
}